package com.itlong.cloud.controller.whitelist;

import com.itlong.cloud.POJO.DTO.operate.OperateDeviceWhiteListDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateDeviceWhiteListSaveDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyCarRowDTO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.operate.DeviceWhiteListDetailVO;
import com.itlong.cloud.POJO.DTO.operate.OperateDeviceWhiteListErrorDTO;
import com.itlong.cloud.POJO.VO.operate.OperateDeviceWhiteListVO;
import com.itlong.cloud.POJO.VO.operate.OperateMacInfoVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.FileCatalogEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.ErrorCode;
import com.itlong.cloud.enumerate.ecode.OperateErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.equip.operate.IOperateDeviceWhiteListServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * <desc>
 *      运营-设备白名单管理控制器
 * </desc>
 *
 * @createDate 2019/12/11
 **/
@RestController
@RequestMapping("/device/whiteList")
public class OperateWhiteListController extends BaseController {

    @Autowired
    IOperateDeviceWhiteListServiceClient iOperateDeviceWhiteListServiceClient;

    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;

    @Autowired
    public RedisService redisService;



    /**
     * <desc>
     *      保存设备白名单信息
     * </desc>
     *
     * @param operateDeviceWhiteListDTO 设备白名单DTO
     * @return
     * @Author Zhu.yj
     * @createDate  2019/12/16
     */
    @LoggerInfo(operateDesc = LogDescConstant.OPERATE_DEVICE_WHITE_LIST_SAVE_LOG_DESC)
    @RequestMapping( value = "save", method = RequestMethod.POST)
    public Object save(OperateDeviceWhiteListDTO operateDeviceWhiteListDTO){
        try {
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            operateDeviceWhiteListDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateDeviceWhiteListDTO.class,request);
            String myUserName = request.getAttribute("myUserName") == null ? null : request.getAttribute("myUserName").toString();
            if (operateDeviceWhiteListDTO == null || StringUtils.isBlank(operateDeviceWhiteListDTO.getMacAddress())
                    || StringUtils.isBlank(myUserName)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //验证白名单信息列表中是否已存在该mac地址
            OperateDeviceWhiteListVO operateDeviceWhiteListVO = iOperateDeviceWhiteListServiceClient.getWhiteListByMac(operateDeviceWhiteListDTO.getMacAddress());
            if (operateDeviceWhiteListVO != null && ("1").equals(operateDeviceWhiteListVO.getChangeFlag())){
                return new MessageVO(OperateErrorCodeEnum.DEVICE_WHITE_LIST_MAC_IS_EXIST.getErrorCode());
            }
            if (operateDeviceWhiteListVO != null && ("2").equals(operateDeviceWhiteListVO.getChangeFlag())){
                return new MessageVO(OperateErrorCodeEnum.DEVICE_EXIST_IN_EXCEPTION_LIST_ERR.getErrorCode());
            }
            operateDeviceWhiteListDTO.setLoginUserId(myUserName);
            Integer result = iOperateDeviceWhiteListServiceClient.save(operateDeviceWhiteListDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), result);
        }catch (Exception e){
            throw new DataAccessException("【运营-设备白名单管理-save】保存设备白名单信息失败",e);
        }
    }

    /**
     * <desc>
     *      分页获取设备白名单信息
     * </desc>
     *
     * @param operateDeviceWhiteListDTO 设备白名单DTO
     * @return
     * @Author Zhu.yj
     * @createDate  2019/12/16
     */
    @RequestMapping(value = "getWhiteListByPage", method = RequestMethod.POST)
    public Object getWhiteListByPage(OperateDeviceWhiteListDTO operateDeviceWhiteListDTO, HttpServletRequest request){
        try {
            operateDeviceWhiteListDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateDeviceWhiteListDTO.class,request);
            if (operateDeviceWhiteListDTO == null || operateDeviceWhiteListDTO.getExceptionFlag() == null){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (!NumberHandlerUtil.isInRange(operateDeviceWhiteListDTO.getExceptionFlag(),1,2)) {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            Page<OperateDeviceWhiteListVO> page = iOperateDeviceWhiteListServiceClient.getWhiteListByPage(operateDeviceWhiteListDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),page);
        }catch(Exception e){
            throw new DataAccessException("【运营-设备白名单管理-getWhiteListByPage】分页获取设备白名单信息失败",e);
        }
    }

    /**
     * <desc>
     *      禁用或删除设备白名单信息
     * </desc>
     *
     * @param operateDeviceWhiteListDTO 设备白名单DTO
     * @return
     * @Author Zhu.yj
     * @createDate  2019/12/16
     */
    @LoggerInfo(operateDesc = LogDescConstant.OPERATE_DEVICE_WHITE_LIST_UPDATE_OR_DELETE_LOG_DESC)
    @RequestMapping( value = "forbidden", method = RequestMethod.POST)
    public Object forbidden(OperateDeviceWhiteListDTO operateDeviceWhiteListDTO){
        try {
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            operateDeviceWhiteListDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateDeviceWhiteListDTO.class,request);
            if (StringUtils.isBlank(operateDeviceWhiteListDTO.getWhiteListId()) || operateDeviceWhiteListDTO.getOperType() == null){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (!NumberHandlerUtil.isInRange(operateDeviceWhiteListDTO.getOperType(),0,2)){
                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
            }
            Integer result = iOperateDeviceWhiteListServiceClient.forbidden(operateDeviceWhiteListDTO);
            if (result == -1){
                return new MessageVO(OperateErrorCodeEnum.ACTIVATED_DEVICE_COULD_NOT_DELETE_ERR.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());

        }catch (Exception e){
            return new DataAccessException("【运营-设备白名单管理forbidden】禁用或删除设备白名单信息失败",e);
        }
    }

    /**
     * <desc>
     *      获取设备白名单详情
     * </desc>
     *
     * @return
     * @Author Zhu.yj
     * @createDate  2020/8/11
     */
    @RequestMapping(value = "getDetail", method = RequestMethod.POST)
    public Object getDetail(HttpServletRequest request){
        try {
            String whiteListId = request.getAttribute("whiteListId") == null ? null : request.getAttribute("whiteListId").toString();
            if(StringUtils.isBlank(whiteListId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            DeviceWhiteListDetailVO deviceWhiteListDetailVO = iOperateDeviceWhiteListServiceClient.getDetail(whiteListId);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), deviceWhiteListDetailVO);
        }catch (Exception e){
            throw new DataAccessException("【运营_设备白名单管理getDetail】获取设备白名单详情失败", e);
        }
    }

    /**
     * <desc>
     *      获取导入模板
     * </desc>
     *
     * @param
     * @return
     * @Author Zhu.yj
     * @createDate  2020/8/11
     */
    @RequestMapping(value = "getImportTemplate", method = RequestMethod.POST)
    public Object getImportTemplate(){
        try{
            String templateFilePath = FILE_ACCESS_URL + FileCatalogEnum.PROJECT_STATIC_FILE.getType()
                    + PlatformConstants.DEVICE_WHITE_LIST_IMPORT_TEMPLATE;
            URI exportTemplateUrl = new URI(templateFilePath);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),(Object)exportTemplateUrl.toString());
        }catch (Exception e){
            throw new DataAccessException("【运营_设备白名单管理getImportTemplate】获取导入模板失败", e);
        }
    }

    /**
     * <desc>
     *      批量导入设备白名单
     * </desc>
     *
     * @return
     * @Author Zhu.yj
     * @createDate  2020/8/11
     */
    @RequestMapping(value = "importWhiteList", method = RequestMethod.POST)
    public Object importWhiteList(HttpServletRequest request){
        try{
            MessageVO messageVO;
            String myUserName = request.getAttribute("myUserName") == null ? null : request.getAttribute("myUserName").toString();
            if (StringUtils.isBlank(myUserName)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (!isMultipart) {
                //是否是带文件上传的表单
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_IMPORT_FILE_LOST_ERR.getErrorCode());
            }
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> multipartFileMap = multipartRequest.getFileMap();
            if (multipartFileMap.size() < 1){
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_IMPORT_FILE_LOST_ERR.getErrorCode());
            }
            if (multipartFileMap.size() > 1){
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_EXCEL_FILE_TOO_MANY_ERR.getErrorCode());
            }
            List<HSSFSheet> availableSheets = new ArrayList<>(); //合法的Sheet页
            //获取excel文件
            Map.Entry<String, MultipartFile> fileEntry = multipartFileMap.entrySet().iterator().next();
            MultipartFile excelFile = fileEntry.getValue();
            String excelFileName = excelFile.getOriginalFilename();
            String excelContentType = StringHandlerUtil.copySubStr(excelFileName, excelFileName.lastIndexOf('.'), excelFileName.length());
            if (!(".xls".equalsIgnoreCase(excelContentType) || ".xlsx".equalsIgnoreCase(excelContentType))) {
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_IMPORT_FILE_TYPE_ERR.getErrorCode());
            }
            List<OperateDeviceWhiteListErrorDTO> errorImportDataList;
            List<OperateDeviceWhiteListSaveDTO> whiteListSaveDTOList;
            //创建Excel操作对象，07之前版本(*.xls)使用HSSFWorkBook 07之后版本使用（*.xlsx）XSSFWorkbook
            POIFSFileSystem fileSystem = new POIFSFileSystem(excelFile.getInputStream());
            try {
                try (HSSFWorkbook workbook = new HSSFWorkbook(fileSystem)) {
                    //对导入文件的数据格式等基本信息进行合法性初步检测
                    messageVO = checkImportFileValid(workbook, availableSheets);
                    if (!messageVO.getMsgCode().equals(BaseErrorCodeEnum.SUCCESS.getErrorCode().getMainCode())) {
                        return messageVO;
                    }
                    //处理Excel文件中的地址数据
                    whiteListSaveDTOList = new ArrayList<>();
                    errorImportDataList = getImportWhiteListFromFile(whiteListSaveDTOList, availableSheets, myUserName);
                }
            } finally {
                fileSystem.close();
            }

            //若有非法数据，返回非法数据
            if (!errorImportDataList.isEmpty()) {
                return new MessageVO(OperateErrorCodeEnum.DEVICE_WHITE_LIST_DATA_ERR.getErrorCode(), errorImportDataList);
            }
            iOperateDeviceWhiteListServiceClient.importDeviceWhiteList(whiteListSaveDTOList);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营_设备白名单管理importWhiteList】批量导入设备白名单失败", e);
        }
    }

    /**
     * <desc>
     *      添加备注
     * </desc>
     *
     * @param operateDeviceWhiteListDTO 设备白名单DTO
     * @return 格式化响应参数
     * @Author Zhu.yj
     * @createDate  2020/9/2
     */
    @RequestMapping(value = "addRemark", method = RequestMethod.POST)
    public Object addRemark(OperateDeviceWhiteListDTO operateDeviceWhiteListDTO, HttpServletRequest request){
        try {
            operateDeviceWhiteListDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateDeviceWhiteListDTO.class, request);
            String myUserName = request.getAttribute("myUserName") == null ? null : request.getAttribute("myUserName").toString();
            if (operateDeviceWhiteListDTO == null || StringUtils.isBlank(operateDeviceWhiteListDTO.getRemark())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            operateDeviceWhiteListDTO.setLoginUserId(myUserName);
            iOperateDeviceWhiteListServiceClient.update(operateDeviceWhiteListDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营_设备白名单管理addRemark】添加备注失败", e);
        }
    }

    /**
     * <desc>
     *      转换为白名单
     * </desc>
     *
     * @param operateDeviceWhiteListDTO 设备白名单DTO
     * @param request
     * @return
     * @Author Zhu.yj
     * @createDate  2020/9/2
     */
    @RequestMapping(value = "convertToWhiteList", method = RequestMethod.POST)
    public Object convertToWhiteList(OperateDeviceWhiteListDTO operateDeviceWhiteListDTO, HttpServletRequest request){
        try {
            operateDeviceWhiteListDTO = HttpProtocolUtil.parseRequestParamToDTO(OperateDeviceWhiteListDTO.class, request);
            String myUserName = request.getAttribute("myUserName") == null ? null : request.getAttribute("myUserName").toString();
            if(operateDeviceWhiteListDTO == null || StringUtils.isBlank(myUserName)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            operateDeviceWhiteListDTO.setLoginUserId(myUserName);
            iOperateDeviceWhiteListServiceClient.convertToWhiteList(operateDeviceWhiteListDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【运营_设备白名单管理addRemark】转换为白名单失败", e);
        }
    }

    /**
     * <desc>
     *      对导入文件的文件格式等基本信息进行合法性初步检测.
     * </desc>
     *
     * @param workbook        Excel操作对象
     * @param availableSheets 合法可用到Sheet页
     * @return MessageVO 标准格式化响应结果
     * @author zhu.yj
     * @createDate 2020-08-11
     */
    private MessageVO checkImportFileValid(HSSFWorkbook workbook, List<HSSFSheet> availableSheets) {

        //获取Excel的Sheet页面数，每个Excel文件至少会有一个Sheet页(Excel文件本身到限定)
        int sheetCount = workbook.getNumberOfSheets();
        int totalRowsCount = 0;
        //遍历当前文件的所有Sheet页，进行合法性检测
        for (int sheetIndex = 0; sheetIndex < sheetCount; sheetIndex++) {

            HSSFSheet oneSheet = workbook.getSheetAt(sheetIndex);
            int rowsCountOfCurrentSheet = oneSheet.getPhysicalNumberOfRows();
            totalRowsCount += rowsCountOfCurrentSheet;
            //导入的地址数量超出限制,提前退出（sheetCount = 1 * sheetCount 代表标题行的数量）
            if (totalRowsCount > PlatformConstants.MAX_IMPORT_ADDRESS_COUNT + sheetCount) {
                ErrorCode errorCode = OperateErrorCodeEnum.DEVICE_WHITE_LIST_IMPORT_TOO_MANY_ERR.getErrorCode();
                return new MessageVO(errorCode,
                        String.format(errorCode.getCodeMsg(), PlatformConstants.MAX_IMPORT_ADDRESS_COUNT));
            }
            if (rowsCountOfCurrentSheet < 1) {
                continue;
            }

            //对当前Sheet的列数量进行合法性判断
            HSSFRow headerRow = oneSheet.getRow(0);
            int columnCount = oneSheet.getRow(0).getPhysicalNumberOfCells();
            if (columnCount != PlatformConstants.DEVICE_WHITE_LIST_TITLES.length) {
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_EXCEL_COLUMN_COUNT_MISMATCH_ERR.getErrorCode());
            }

            //每个Sheet页的第一页为列标题，进行标题头名称进行合法性判断
            DataFormatter dataFormatter = new DataFormatter();
            for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
                String oneFieldValue = dataFormatter.formatCellValue(headerRow.getCell(columnIndex));

                String columnTitle = PlatformConstants.DEVICE_WHITE_LIST_TITLES[columnIndex];
                if (!StringHandlerUtil.compareStrWithOutEmpty(oneFieldValue, columnTitle)) {
                    ErrorCode errorCode = OperateErrorCodeEnum.DEVICE_WHITE_LIST_IMPORT_FILE_ERR.getErrorCode();
                    return new MessageVO(errorCode,
                            String.format(errorCode.getCodeMsg(), oneFieldValue, columnTitle));
                }
            }
            //至少有一行实际数据可导入才加入Sheet处理列表
            if (rowsCountOfCurrentSheet > 1) {
                availableSheets.add(oneSheet);
            }

        }//end Sheet遍历

        //没有数据
        if (availableSheets.isEmpty()) {
            return new MessageVO(PropertyErrorCodeEnum.PROJECT_IMPORT_FILE_NO_DATA_ERR.getErrorCode());
        }
        return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
    }

    /**
     * <desc>
     *      从可用sheet页中解析设备白名单信息
     * </desc>
     *
     * @param whiteListSaveDTOList 从Excel(*.xls)中导入的设备白名单信息传输对象列表
     * @param availableSheets 可用的sheet页
     * @return
     * @Author Zhu.yj
     * @createDate  2020/8/11
     */
    private List<OperateDeviceWhiteListErrorDTO> getImportWhiteListFromFile(List<OperateDeviceWhiteListSaveDTO> whiteListSaveDTOList, List<HSSFSheet> availableSheets , String loginUserId) throws Exception{
        // Excel单元格数据操作对象
        DataFormatter dataFormatter = new DataFormatter();
        // 错误的行信息列表
        List<OperateDeviceWhiteListErrorDTO> errorImportDataList = new ArrayList<>();
        //取出所有设备白名单mac地址信息
        List<OperateMacInfoVO> macList = iOperateDeviceWhiteListServiceClient.getMacList();
        int totalRowsCount = 0;
        int currentRow = 1;
        List<String> currentMacList = new ArrayList<>();
        for (HSSFSheet oneSheet : availableSheets) {
            int rowsCountOfCurrentSheet = oneSheet.getPhysicalNumberOfRows();
            totalRowsCount += rowsCountOfCurrentSheet;
            if (totalRowsCount > 1000) {
                return null;
            }
            SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.DEFAULTF);
            System.out.println("开始解析导入数据时间"+sdf.format(System.currentTimeMillis()));
            for (int rowIndex = 1; rowIndex < rowsCountOfCurrentSheet; rowIndex++) {
                int percent = currentRow/totalRowsCount * 100;
                HSSFRow row = oneSheet.getRow(rowIndex);
                //对当前Sheet中的当前行进行数据处理,逐行处理设备白名单中错误的数据
                OperateDeviceWhiteListErrorDTO errorDTO = this.handleOneRowWhiteListInfo(row,whiteListSaveDTOList,dataFormatter,macList, currentMacList, loginUserId);
                //若存在错误信息，则将加入错误列表
                if (!errorDTO.getErrorCodes().isEmpty()) {
                    this.addErrorDeviceWhiteListToList(errorImportDataList,errorDTO);
                }
            }
            System.out.println("解析完成时间"+sdf.format(System.currentTimeMillis()));
        }
        return errorImportDataList;
    }

    /**
     * <desc>
     *      处理一行excel的数据
     * </desc>
     *
     * @param hssfRow Excel的一行数据
     * @param whiteListSaveDTOList 从Excel(*.xls)导入设备二维码信息数据传输对象列表
     * @param dataFormatter Excel单元格数据的读取器
     * @param macList mac地址列表
     * @return
     * @Author Zhu.yj
     * @createDate  2020/8/11
     */
    private OperateDeviceWhiteListErrorDTO handleOneRowWhiteListInfo(HSSFRow hssfRow, List<OperateDeviceWhiteListSaveDTO> whiteListSaveDTOList, DataFormatter dataFormatter, List<OperateMacInfoVO> macList, List<String> currentMacList, String loginUserId) throws Exception{

        OperateDeviceWhiteListErrorDTO whiteListErrorDTO = new OperateDeviceWhiteListErrorDTO();
        OperateDeviceWhiteListSaveDTO whiteListSaveDTO = new OperateDeviceWhiteListSaveDTO();
        List<ErrorCode> errorCodes = whiteListErrorDTO.getErrorCodes();
        // 首先登记所属的Sheet名称和行号
        whiteListErrorDTO.setSheetName(hssfRow.getSheet().getSheetName());
        whiteListErrorDTO.setRowNum(hssfRow.getRowNum() + 1);
//        //处理设备类型 /*产品更改需求，导入时不添加设备类型，设备类型由设备激活成功后返回
//        String deviceType = dataFormatter.formatCellValue(hssfRow.getCell(0));
//        whiteListErrorDTO.setDeviceType(deviceType);
        //处理mac地址
        String macAddress = dataFormatter.formatCellValue(hssfRow.getCell(0));
        whiteListErrorDTO.setMacAddress(macAddress);
        macAddress = macAddress.replace("-",":");
        //处理备注
        String remark = dataFormatter.formatCellValue(hssfRow.getCell(1));
        whiteListErrorDTO.setRemark(remark);
        if (StringUtils.isBlank(macAddress)){
            return whiteListErrorDTO;
        }
        for (OperateMacInfoVO operateMacInfoVO : macList) {
            //设备白名单中有此设备
            if (macAddress.equals(operateMacInfoVO.getMacAddress())) {
                if (("1").equals(operateMacInfoVO.getChangeFlag())) {
                    errorCodes.add(OperateErrorCodeEnum.DEVICE_WHITE_LIST_HAVE_MAC_ADDRESS_YET_ERR.getErrorCode());
                    break;
                }
                if (("2").equals(operateMacInfoVO.getChangeFlag())){
                    errorCodes.add(OperateErrorCodeEnum.DEVICE_EXIST_IN_EXCEPTION_LIST_ERR.getErrorCode());
                }
            }
        }
        if (currentMacList.contains(macAddress)){
            errorCodes.add(OperateErrorCodeEnum.IMPORT_FILE_REPEAT_MAC_ADDRESS.getErrorCode());
        }
        //对输入的mac地址进行格式校验
        Pattern pattern = Pattern.compile("([0-9a-fA-F]{2})(([/\\s:][0-9a-fA-F]{2}){5})$");
        if (!pattern.matcher(macAddress).matches()){
            errorCodes.add(OperateErrorCodeEnum.MAC_ADDRESS_FORMAT_ERR.getErrorCode());
        }
        currentMacList.add(macAddress);
        if (!errorCodes.isEmpty()){
            return whiteListErrorDTO;
        }
        whiteListSaveDTO.setMacAddress(macAddress);
        whiteListSaveDTO.setLoginUserId(loginUserId);
        whiteListSaveDTO.setRemark(remark);
        whiteListSaveDTOList.add(whiteListSaveDTO);
        return whiteListErrorDTO;
    }

    /**
     * <desc>
     *      将错误的设备白名单信息添加到错误列表中
     * </desc>
     *
     * @param errorImportDataList 错误数据列表
     * @param errorDTO  有错误的数据
     * @return
     * @Author Zhu.yj
     * @createDate  2020/8/11
     */
    private void addErrorDeviceWhiteListToList(List<OperateDeviceWhiteListErrorDTO> errorImportDataList, OperateDeviceWhiteListErrorDTO errorDTO) {
        for (OperateDeviceWhiteListErrorDTO oneAddressInfo:errorImportDataList){
            if ((oneAddressInfo.getRowNum().equals(errorDTO.getRowNum()))
                    && (StringHandlerUtil.compareStrWithOutEmpty(oneAddressInfo.getSheetName(),errorDTO.getSheetName()))){
                return;
            }
        }
        errorImportDataList.add(errorDTO);
    }
}
